package cz.muni.fi.pa165.sme.web.common;

import cz.muni.fi.pa165.sme.api.UserService;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

/**
 * Validates login if it is not null, empty, and if it is available.
 * @author jirankova */
public class LoginValidator implements IValidator<String> {

	private UserService userService;

	public LoginValidator(final UserService userService) {
		this.userService = userService;
	}

	@Override
	public void validate(final IValidatable<String> validatable) {
		final String login = validatable.getValue();

		if(login == null || login.isEmpty()) {
			final ValidationError emptyLogin = new ValidationError();
			emptyLogin.addMessageKey("emptyLogin");
			validatable.error(emptyLogin);
			return;
		}

		if(!userService.isLoginAvailable(login)) {
			final ValidationError unavailableLogin = new ValidationError();
			unavailableLogin.addMessageKey("unavailableLogin");
			validatable.error(unavailableLogin);
		}
	}
}
